package com.glasses.business.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.glasses.business.R;
import com.glasses.business.appliction.MyApplication;
import com.glasses.business.base.BaseActivity;
import com.glasses.business.entity.User;
import com.glasses.business.http.NetUtils;
import com.glasses.business.pay.com.ConstantKeys;
import com.glasses.business.utils.HttpCallBackListener;
import com.glasses.business.utils.HttpUtil;
import com.glasses.business.utils.PrefParams;
import com.glasses.business.utils.Tools;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import net.neiquan.okhttp.NetCallBack;
import net.neiquan.okhttp.ResultModel;

import org.haitao.common.utils.AppLog;
import org.haitao.common.utils.RegexValidateUtil;
import org.haitao.common.utils.ToastUtil;
import org.json.JSONException;
import org.json.JSONObject;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;

/**
 * Created by cxh on 2016/9/9.
 */
public class LoginActiviy extends BaseActivity {
    @InjectView(R.id.phoneEdt)
    EditText phoneEdt;
    @InjectView(R.id.codeEdt)
    EditText codeEdt;
    @InjectView(R.id.getCodeLL)
    LinearLayout getCodeLL;
    @InjectView(R.id.loginTv)
    TextView loginTv;
    @InjectView(R.id.codeTv)
    TextView codeTv;
    @InjectView(R.id.wxLogin)
    ImageView wxLogin;
    private String phone;
    private ReceiveBroadCast receiveBroadCast;
    private IWXAPI api;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
//                WindowManager.LayoutParams.FLAG_FULLSCREEN);  //全屏
        setContentView(R.layout.activity_login);
        ButterKnife.inject(this);
        MyApplication.getInstance().manager = null;
        setTitleTv("登录");
        setBackGone();
        setNextImage(R.mipmap.icon_back);
        setNextOnClick(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

    }

    @Override
    protected void onPause() {
        super.onPause();
        JPushInterface.onPause(this);
    }

    @OnClick({R.id.getCodeLL, R.id.loginTv, R.id.wxLogin})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.getCodeLL:
                getCode();
                break;
            case R.id.loginTv:
                login();
                break;
            case R.id.wxLogin:
                weChatAuth();
                break;
        }
    }

    private void wxLogin(String openId,String userAcount) {
//        Tools.showDialog(this);
        NetUtils.getInstance().wxLogin(openId, userAcount, JPushInterface.getRegistrationID(this),new NetCallBack() {
            @Override
            public void onSuccess(String response, String mssage, ResultModel model) {
//                Tools.dismissWaitDialog();
                ToastUtil.shortShowToast(mssage);
                MyApplication.getInstance().saveUser(((User) model.getModel()));
                Intent intent = new Intent(LoginActiviy.this, MainActivity.class);
                startActivity(intent);
            }

            @Override
            public void onFail(boolean dataError, int errorCode, String mssage) {
//                Tools.dismissWaitDialog();
                ToastUtil.shortShowToast(mssage);
            }
        }, User.class);
    }

    private void login() {
        JPushInterface.getRegistrationID(this);
        AppLog.e("============111==========="+JPushInterface.getRegistrationID(this));
        phone = phoneEdt.getText().toString();
        String mCode = codeEdt.getText().toString();
        if (!RegexValidateUtil.checkCellphone(phone)) {
            ToastUtil.shortShowToast("请输入正确的手机号码...");
        } else if (!mCode.equals(code)) {
            ToastUtil.shortShowToast("请输入正确的验证码...");
        } else {
            Tools.showDialog(this);
            NetUtils.getInstance().login(phone, this.code, JPushInterface.getRegistrationID(this), new NetCallBack() {
                @Override
                public void onSuccess(String response, String mssage, ResultModel model) {
                    Tools.dismissWaitDialog();
                    ToastUtil.shortShowToast(mssage);
                    User user = (User) model.getModel();
                    MyApplication.getInstance().saveUser(user);
                    startActivity(new Intent(LoginActiviy.this, MainActivity.class));
                    finish();
                }

                @Override
                public void onFail(boolean dataError, int errorCode, String mssage) {
                    Tools.dismissWaitDialog();
                    ToastUtil.shortShowToast(mssage);
                }
            }, User.class);
        }
    }

    private boolean flag;
    private CountDownTimer mTimer;// 倒计时；
    private String code;

    /**
     * 获取验证码
     */
    private void getCode() {
        if (flag) {
            ToastUtil.shortShowToast("验证码已经发送过了");
        } else {
            phone = phoneEdt.getText().toString();
            if (RegexValidateUtil.checkCellphone(phone)) {
                Tools.showDialog(this);
                codeTv.setClickable(false);
                //0：注册 1：修改密码
                NetUtils.getInstance().getCaptcha(phone, null, new NetCallBack() {
                    @Override
                    public void onSuccess(String response, String mssage, ResultModel model) {
                        Tools.dismissWaitDialog();
                        ToastUtil.shortShowToast(mssage);
                        code = response;
                        flag = true;
                        codeTv.setClickable(true);
                        startTimmer();
                    }

                    @Override
                    public void onFail(boolean dataError, int errorCode, String mssage) {
                        Tools.dismissWaitDialog();
                        codeTv.setClickable(true);
                        ToastUtil.shortShowToast(mssage);
                    }

                }, String.class);

            } else {
                ToastUtil.shortShowToast("请输入正确的手机号码...");
            }
        }
    }

    private void startTimmer() {
        mTimer = new CountDownTimer(60000, 1000) {

            @Override
            public void onTick(long millisUntilFinished) {
                codeTv.setText(millisUntilFinished / 1000 + "秒后重发");
            }

            @Override
            public void onFinish() {
                flag = false;
                codeTv.setText("获取验证码");
            }
        };
        mTimer.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mTimer != null) {
            mTimer.cancel();
            mTimer.onFinish();
        }
        ButterKnife.reset(this);
        if (receiveBroadCast != null) {
            unregisterReceiver(receiveBroadCast);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        JPushInterface.onResume(this);
        receiveBroadCast = new ReceiveBroadCast();
        IntentFilter filter = new IntentFilter();
        filter.addAction("authlogin");
        registerReceiver(receiveBroadCast, filter);
    }


    private void weChatAuth() {
        if (api == null) {
            api = WXAPIFactory.createWXAPI(this, ConstantKeys.WxPay.APP_ID, true);
        }
        SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "wx_login_duzun";
        api.sendReq(req);
    }

    public void getAccessToken() {
        SharedPreferences WxSp = getApplicationContext()
                .getSharedPreferences(PrefParams.spName, Context.MODE_PRIVATE);
        String code = WxSp.getString(PrefParams.CODE, "");
        final SharedPreferences.Editor WxSpEditor = WxSp.edit();
        AppLog.e("-----获取到的code----" + code);
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
                + ConstantKeys.WxPay.APP_ID
                + "&secret="
                + ConstantKeys.WxPay.APP_SECRET
                + "&code="
                + code
                + "&grant_type=authorization_code";
        AppLog.e("--------即将获取到的access_token的地址--------");
        HttpUtil.sendHttpRequest(url, new HttpCallBackListener() {
            @Override
            public void onFinish(String response) {

                //解析以及存储获取到的信息
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    AppLog.e("-----获取到的json数据1-----" + jsonObject.toString());
                    String access_token = jsonObject.getString("access_token");
                    AppLog.e("--------获取到的access_token的地址--------" + access_token);
                    String openid = jsonObject.getString("openid");
                    String refresh_token = jsonObject.getString("refresh_token");
                    if (!access_token.equals("")) {
                        WxSpEditor.putString(PrefParams.ACCESS_TOKEN, access_token);
                        WxSpEditor.apply();
                    }
                    if (!refresh_token.equals("")) {
                        WxSpEditor.putString(PrefParams.REFRESH_TOKEN, refresh_token);
                        WxSpEditor.apply();
                    }
                    if (!openid.equals("")) {
                        WxSpEditor.putString(PrefParams.WXOPENID, openid);
                        WxSpEditor.apply();
                        getPersonMessage(access_token, openid);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Exception e) {
                Toast.makeText(LoginActiviy.this, "通过code获取数据没有成功", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void getPersonMessage(String access_token, String openid) {
        String url = "https://api.weixin.qq.com/sns/userinfo?access_token="
                + access_token
                + "&openid="
                + openid;
        HttpUtil.sendHttpRequest(url, new HttpCallBackListener() {
            @Override
            public void onFinish(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    AppLog.e("------获取到的个人信息------" + jsonObject.toString());
                    wxLogin(jsonObject.getString("openid"),jsonObject.getString("nickname"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Exception e) {
                Toast.makeText(LoginActiviy.this, "通过openid获取数据没有成功", Toast.LENGTH_SHORT).show();
            }
        });
    }

    class ReceiveBroadCast extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            getAccessToken();
        }
    }
}
